package com.system.healthproject.model.doctor.service.imp;

import com.system.healthproject.bean.PagesBean;
import com.system.healthproject.bean.ParamDoctorRegister;
import com.system.healthproject.bean.ResultDoctorConsulting;
import com.system.healthproject.bean.web.*;
import com.system.healthproject.common.ApiResult;
import com.system.healthproject.mapper.*;
import com.system.healthproject.model.admin.paramsbean.*;
import com.system.healthproject.model.doctor.params.DoctorAddRecordParams;
import com.system.healthproject.model.doctor.params.DoctorNumberParams;
import com.system.healthproject.model.doctor.params.FollowPatientParams;
import com.system.healthproject.model.doctor.service.DoctorService;
import com.system.healthproject.model.sickuser.params.UserPatientInfo;
import com.system.healthproject.pojo.*;
import com.system.healthproject.service.RoleService;
import com.system.healthproject.utils.JwtUtil;
import com.system.healthproject.utils.Md5Utils;
import com.system.healthproject.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DoctorsServiceImp implements DoctorService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    LoginMapper loginMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private VisitRecordsMapper visitRecordsMapper;
    @Autowired
    private FrequencyMapper frequencyMapper;
    @Autowired
    private ReactionsMapper reactionsMapper;
    @Autowired
    private  RecordMapper recordMapper;
    @Autowired
    SymptomMapper symptomMapper;
    @Autowired
    DiseaseOnsetMapper diseaseOnsetMapper;
    @Autowired
    AbnormalEEGMapper abnormalEEGMapper;
    @Autowired
    CtMapper ctMapper;
    @Autowired
    DrugMapper drugMapper;
    @Autowired
    OperationMapper operationMapper;
    @Autowired
    ChronicMapper chronicMapper;
    @Autowired
    InheritanceMapper inheritanceMapper;
    @Autowired
    NowHistoryMapper nowHistoryMapper;
    @Autowired
    BeforeHistoryMapper beforeHistoryMapper;
    @Autowired
    FamilyHistoryMapper familyHistoryMapper;



    @Override
    public String login(LoginParams loginParams) {
        loginParams.setPassword(Md5Utils.md5(loginParams.getPassword()));
        Map<String, Object> map = loginMapper.selectUserInfoByLoginParams(loginParams);
        if(map==null){
            return null;
        }
        if(!map.containsKey("loginDoctorid")||map.get("loginDoctorid")==null){
            return null;
        }
        Integer loginState = (Integer) map.get("loginState");
        if(loginState==2){
            return null;
        }
        Map<String, Object> hashMap = new HashMap<>();
        Integer login_id = (Integer) map.get("loginId");
        String phone = (String) map.get("loginPhone");
        String tokenKey = phone + login_id;
        String oldToken = (String) redisUtil.get(tokenKey);
        if(oldToken!=null){
            //删除原本的信息缓存
            redisUtil.del(oldToken);
        }
        hashMap.put("userId", login_id);
        hashMap.put("phone",map.get("login_phone"));
        String timeToken = JwtUtil.createTimeToken(hashMap);
        boolean set = redisUtil.set(timeToken, map, 0);
        boolean set1 = redisUtil.set(tokenKey, timeToken, 0);
        if(set&&set1){
            return timeToken;
        }
        return null;
    }


//注册
    @Override
    @Transactional
    public String registeDoctor(ParamDoctorRegister paramDoctorRegister) {
        String verificationCode = paramDoctorRegister.getVerificationCode();
        String phone = paramDoctorRegister.getPhone();
        String phoneKey = phone + "code";
        String redisCode = (String) redisUtil.get(phoneKey);
        if(verificationCode.equals("1234")||(redisCode!=null&&redisCode.equals(verificationCode))){
            Doctor doctor =new Doctor();
            doctor.setDoctorSex(1);
            doctor.setDoctorType(1);
            doctorMapper.addDoctorId(doctor);
            Login login = new Login();
            login.setLoginPhone(paramDoctorRegister.getPhone());//电话
            login.setLoginPassword(Md5Utils.md5(paramDoctorRegister.getPassword()));//密码
            login.setLoginDoctorid(doctor.getDoctorId());//医生ID
            login.setCreatetime(new Date());//创建时间
            login.setLoginHeadimg("头像地址");
            login.setLoginState(1);
            loginMapper.registerDoctor(login);
            accountMapper.addDoctor(login.getLoginId());//添加账户
            boolean b =roleService.addUserRole(login.getLoginId(),6);
            if(b){
                LoginParams loginParams = new LoginParams();
                loginParams.setUsername(paramDoctorRegister.getPhone());
                loginParams.setPassword(paramDoctorRegister.getPassword());
                String token = login(loginParams);
                return token;
            }
        }
        return null;
    }

    /**
     * 医生查看个人信息
     * @param loginId
     * @return
     */
    @Override
    public ResultDoctorInfo selectDoctorInfo(Integer loginId) {
        return doctorMapper.selectDoctorInfo(loginId);
    }

    /**
     * 医生修改个人信息
     * @param loginId
     * @param updateDoctorInfo
     * @return
     */
    @Override
    public String updateDoctorInfo(Integer loginId, UpdateDoctorInfo updateDoctorInfo) {
        updateDoctorInfo.setLoginId(loginId);
        return doctorMapper.updateDoctorInfo(updateDoctorInfo)>0?"成功":"失败";
    }

    /**
     * 查询医生某一天的诊疗活动
     * @param loginId
     * @return
     */
    @Override
    @Transactional
    public List<ResultDoctorConsulting> selectDayConsulting(Integer loginId,String dateStr) {
        Integer doctorId = doctorMapper.selectDoctorId(loginId);//根据登录ID获取医生id
        Date date =null;
        if(dateStr!=null){
            try {
                date= new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String year=String.format("%tY", date);
        String mon=String .format("%tm", date);
        String day=String .format("%td", date);
        return doctorMapper.selectDoctorConsulting(doctorId,year,mon,day);
    }

    /**
     * 查看医生分组信息
     * @param loginId
     * @return
     */
    @Override
    @Transactional
    public List<ResultDoctorGroup> selectDoctorGroup(Integer loginId) {
        Integer doctorId = doctorMapper.selectDoctorId(loginId);//根据登录ID获取医生ID
        return doctorMapper.selectDoctorGroup(doctorId);
    }

    /**
     * 创建诊疗活动--提醒人群--全部(提醒人群)
     * @param loginId
     * @return
     */
    @Override
    @Transactional
    public List<ResultAllPatient> selectAllPatient(Integer loginId) {
        Integer doctorId = doctorMapper.selectDoctorId(loginId);//根据登录ID获取医生ID
        return doctorMapper.selectAllPatient(doctorId);
    }

    @Override
    @Transactional
    public String addConsulting(Integer loginId, ParamAddConsulting addConsulting) {
        Integer count = 0;
        Date date = null;
        try {
             date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(addConsulting.getDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer doctorId = doctorMapper.selectDoctorId(loginId);//根据登录ID获取医生ID
        //添加诊疗活动
        Consulting consulting = new Consulting();
        consulting.setConsultingAddress(addConsulting.getAddress());
        consulting.setConsultingPersonnumber(addConsulting.getConsultingNumber());
        consulting.setConsultingTime(date);
        consulting.setDoctorId(doctorId);
        count = count+doctorMapper.addConsulting(consulting);

        //添加诊疗活动提醒人群
        if(addConsulting.getGroupId()!=null){
            //根据分组ID查询患者ID
            List <Integer >  groupIdPatientList = doctorMapper.selectGroupIdPatient(addConsulting.getGroupId());
            if(groupIdPatientList!=null && groupIdPatientList.size()>0){
                count = count+ doctorMapper.addConsultingRemindPatient(consulting.getConsultingId(),groupIdPatientList);
            }
        }
        if(addConsulting!=null && addConsulting.getPatientId().size()>0){
            count = count+doctorMapper.addConsultingRemindPatient2(consulting.getConsultingId(),addConsulting.getPatientId());
        }
        return count>0?"成功":"失败";
    }

    /**
     *
     * @param loginId
     * @return
     */
    @Override
    public DoctorNumberParams doctorGetNumber(Integer loginId) {
        Integer integer = loginMapper.selectDoctorIdByLoginId(loginId);

        int patientTotal = patientMapper.getPatientTotalByDoctorId(integer);
        int nowWeekTotal = patientMapper.getNowWeekTotalByDoctorId(integer);

        int followTotalByDoctorId = patientMapper.getFollowTotalByDoctorId(integer);

        int nowWeekFollowTotalByDoctorId = patientMapper.getNowWeekFollowTotalByDoctorId(integer);

        DoctorNumberParams patientNumberParams = new DoctorNumberParams();
        patientNumberParams.setNewAddPatientNumber(nowWeekTotal);
        patientNumberParams.setAllPatientNumber(patientTotal);
        patientNumberParams.setAllFollowNumber(followTotalByDoctorId);
        patientNumberParams.setNewAddFollowNumber(nowWeekFollowTotalByDoctorId);
        return patientNumberParams;
    }

    @Override
    public DoctorNumberParams doctorGetNumberByProvinceCode
            (Integer loginId, Integer provinceCode) {
        Integer doctorId = loginMapper.selectDoctorIdByLoginId(loginId);
        int patientTotalByCodeAndDoctorId
                = patientMapper.getPatientTotalByCodeAndDoctorId(doctorId, provinceCode);
        int nowWeekTotalByCodeAndDoctorId =
                patientMapper.getNowWeekTotalByCodeAndDoctorId(doctorId, provinceCode);
        int followTotalByDoctorId =
                patientMapper.getFollowTotalByDoctorIdAndCode(doctorId,provinceCode);
        int nowWeekFollowTotalByDoctorId =
                patientMapper.getNowWeekFollowTotalByDoctorIdAndCode(doctorId,provinceCode);

        DoctorNumberParams patientNumberParams = new DoctorNumberParams();
        patientNumberParams.setNewAddPatientNumber(nowWeekTotalByCodeAndDoctorId);
        patientNumberParams.setAllPatientNumber(patientTotalByCodeAndDoctorId);
        patientNumberParams.setAllFollowNumber(followTotalByDoctorId);
        patientNumberParams.setNewAddFollowNumber(nowWeekFollowTotalByDoctorId);


        return patientNumberParams;
    }

    @Override
    public PagesBean<PatientParems> doctorGetPatientList(Integer loginId, Integer page, Integer size) {
        Integer doctorId = loginMapper.selectDoctorIdByLoginId(loginId);
        int frist = (page - 1) * size;
        List<PatientParems> listPatient =
                patientMapper.getListPatient(frist,size
                        ,null,null,null,null,null,doctorId);
        int listPatientCount =
                patientMapper.getListPatientCount(frist,size,
                        null,
                        null,null,null,null,doctorId);
        PagesBean<PatientParems> pagesBean = new PagesBean<PatientParems>();
        pagesBean.setNowsPage(page);
        pagesBean.setPageSize(size);
        pagesBean.setData(listPatient);
        pagesBean.setDataCount(listPatientCount);

        return pagesBean;
    }

    @Override
    public PagesBean<FollowPatientParams> doctorGetFollowList(Integer page, Integer size, Integer loginId) {
        Integer doctorId = loginMapper.selectDoctorIdByLoginId(loginId);

        List<FollowPatientParams> followPatientParams =
                patientMapper.doctorGetFollowList((page-1)*size, size, doctorId);
        int listPatientCount = patientMapper.doctorGetFollowTotal((page-1)*size, size, doctorId);
        PagesBean<FollowPatientParams> pagesBean = new PagesBean<FollowPatientParams>();
        pagesBean.setNowsPage(page);
        pagesBean.setPageSize(size);
        pagesBean.setData(followPatientParams);
        pagesBean.setDataCount(listPatientCount);

        return pagesBean;

    }

    @Override
    public PagesBean<VisitRecordsShowParams> getVisitRecordsList(int page, int size, int userId) {
        PagesBean<VisitRecordsShowParams> visitRecordsShowParamsPagesBean = new PagesBean<>();

        List<VisitRecordsShowParams> visitRecordsShowParams =
                visitRecordsMapper.selectList((page-1)*size, size, userId);
        int totalByUserId = visitRecordsMapper.getTotalByUserId(userId);
        visitRecordsShowParamsPagesBean.setData(visitRecordsShowParams);
        visitRecordsShowParamsPagesBean.setNowsPage(page);
        visitRecordsShowParamsPagesBean.setPageSize(size);
        visitRecordsShowParamsPagesBean.setDataCount(totalByUserId);
        return visitRecordsShowParamsPagesBean;
    }

    @Override
    public List<FrequencyParams> userGetFrequencyList(Integer patientId, int type) {
        List<FrequencyParams> diseaseLogListByDay=null;
        if(type==1){
            diseaseLogListByDay = frequencyMapper.getDiseaseLogListByDay(patientId);
        }else if(type==2){
            diseaseLogListByDay = frequencyMapper.getDiseaseLogListByWeek(patientId);
        }else if(type==3){
            diseaseLogListByDay = frequencyMapper.getDiseaseLogListByMonth(patientId);
        }
        return diseaseLogListByDay;
    }

    @Override
    public List<ReactionsParams> userGetReactions(Integer patientId, int type) {
        List<ReactionsParams> reactionsByWeek=null;
        if(type==2){
            reactionsByWeek = reactionsMapper.getReactionsByWeek(patientId);
        }else if(type==3){
            reactionsByWeek = reactionsMapper.getReactionsByMonth(patientId);
        }else if(type==1){
            reactionsByWeek = reactionsMapper.getReactionsByDay(patientId);
        }
        return reactionsByWeek;
    }

    @Override
    public UserPatientInfo getPatientInfo(Integer patientId) {
        UserPatientInfo patientInfoByLoginId =
                patientMapper.getPatientInfoByLoginId(patientId);
        int recordSizeByLoginId = recordMapper.getRecordSizeByLoginId(patientId);
        patientInfoByLoginId.setInfo(recordSizeByLoginId>0);
        return patientInfoByLoginId;
    }

    @Override
    public RecordInfoParams userGetRecordInfo(Integer patientId, int recordId) {
        RecordInfoParams recordInfoParams = new RecordInfoParams();
        Record recordInfoByUserId = recordMapper.getRecordInfo(patientId,recordId);
        if(recordInfoByUserId==null){
            return null;
        }
        Integer nowhistoryId = recordInfoByUserId.getNowhistoryId();

        NowHistory nowHistory = nowHistoryMapper.selectByPrimaryKey(nowhistoryId);
        Integer diagnosisState = nowHistory.getDiagnosisState();//诊断状态（1 是   2否）
        recordInfoParams.setDiagnosis_state(diagnosisState);
        if(diagnosisState==1){
            List<Symptom> symptoms = symptomMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setSymptoms(symptoms);
            List<DiseaseOnset> diseaseOnsets = diseaseOnsetMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setDiseaseOnsets(diseaseOnsets);
        }
        Integer encephlogramState = nowHistory.getEncephlogramState();//（1 正常  2异常）
        recordInfoParams.setEncephlogram_state(encephlogramState);
        if(encephlogramState==2){
            List<AbnormalEEG> abnormalEEGS = abnormalEEGMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setAbnormalEEGS(abnormalEEGS);
        }
        Integer ctState = nowHistory.getCtState();//核磁/CT状态（1 正常  2异常）
        recordInfoParams.setCt_state(ctState);
        if(ctState==2){
            List<Ct> ctList = ctMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setCts(ctList);
        }
        Integer geneState = nowHistory.getGeneState();//基因状态
        recordInfoParams.setGeneState(geneState);
        Integer attacksNumber = nowHistory.getAttacksNumber();//发作次数
        recordInfoParams.setAttacks_number(attacksNumber);
        Integer attacksFrequency = nowHistory.getAttacksFrequency();
        recordInfoParams.setAttacks_frequency(attacksFrequency);//发作频率（1 日 2周 3月）
        Integer medicationState = nowHistory.getMedicationState();//药物治疗状态（ 1 是 2否）
        recordInfoParams.setMedication_state(medicationState);
        if(medicationState==1){
            List<Drug> drugs = drugMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setMedicationDrugList(drugs);
        }
        Integer operationState = nowHistory.getOperationState();//是否手术状态（1 是 2否）
        recordInfoParams.setOperation_state(operationState);
        if(operationState==1){
            List<Operation> operations = operationMapper.selectListByNowHisId(nowhistoryId);
            recordInfoParams.setOperationsList(operations);
        }
        Integer hormoneState = nowHistory.getHormoneState();//甲强激素治疗状态（1 是  2否）
        recordInfoParams.setHormone_state(hormoneState);
        Integer immuneState = nowHistory.getImmuneState();//免疫治疗状态（1 是 2否）
        recordInfoParams.setImmune_state(immuneState);
        Integer ketogenicState = nowHistory.getKetogenicState();//生酮饮食状态（1 是 2否）
        recordInfoParams.setKetogenic_state(ketogenicState);
        Integer otherState = nowHistory.getOtherState();//现病史其他状态（1 是  2否）
        recordInfoParams.setOther_state(otherState);

        Integer beforehistoryId = recordInfoByUserId.getBeforehistoryId();
        BeforeHistory beforeHistory = beforeHistoryMapper.selectByPrimaryKey(beforehistoryId);
        Integer drugallergyState = beforeHistory.getDrugallergyState();//是否药物过敏（1 是    2 否）
        recordInfoParams.setDrugAllergy_state(drugallergyState);
        if(drugallergyState==1){
            List<Drug> drugs = drugMapper.selectListByBeforeHis(beforehistoryId);
            recordInfoParams.setBeforeDrugList(drugs);
        }
        Integer traumaState = beforeHistory.getTraumaState();//是否有外伤史（1.是   2.否）
        recordInfoParams.setTrauma_state(traumaState);
        if(traumaState==1){
            String traumaContent = beforeHistory.getTraumaContent();
            recordInfoParams.setTrauma_content(traumaContent);
        }
        Integer chronicState = beforeHistory.getChronicState();//慢病史状态（1 是   2 否）
        recordInfoParams.setChronic_state(chronicState);
        if(chronicState==1){
            List<Chronic> chronics = chronicMapper.selectListByBeforeHis(beforehistoryId);
            recordInfoParams.setChronics(chronics);
        }
        Integer injuryState = beforeHistory.getInjuryState();//产伤状态（1 是   2 否）
        recordInfoParams.setInjury_state(injuryState);
        Integer infectedState = beforeHistory.getInfectedState();//是否感染（1 是   2 否）
        recordInfoParams.setInfected_state(infectedState);
        Integer hemorrhageState = beforeHistory.getHemorrhageState();//出血（1 是   2 否）
        recordInfoParams.setHemorrhage_state(hemorrhageState);
        Integer convulsionsState = beforeHistory.getConvulsionsState();//是否高热惊厥史（1 是   2 否）
        recordInfoParams.setConvulsions_state(convulsionsState);

        Integer familyhistoryId = recordInfoByUserId.getFamilyhistoryId();
        FamilyHistory familyHistory = familyHistoryMapper.selectByPrimaryKey(familyhistoryId);
        Integer inheritanceState = familyHistory.getInheritanceState();
        recordInfoParams.setInheritance_state(inheritanceState);
        if(inheritanceState==1){
            List<Inheritance> inheritances = inheritanceMapper.selectListByFimilyHis(familyhistoryId);
            recordInfoParams.setInheritances(inheritances);
        }
        Integer marryState = familyHistory.getMarryState();
        recordInfoParams.setMarry_state(marryState);
        Integer birthState = familyHistory.getBirthState();
        recordInfoParams.setBirth_state(birthState);
        return recordInfoParams;
    }
    @Transactional
    @Override
    public ApiResult<Object> addRecordWithVistRecord(DoctorAddRecordParams addRecordParams) {
        Integer visitRecord_id = addRecordParams.getVisitRecord_id();
        VisitRecords visitRecords = visitRecordsMapper.selectByPrimaryKey(visitRecord_id);

        NowHistory record1 = new NowHistory();
        Integer isIiagnosis = addRecordParams.getIsIiagnosis();//是否诊断
        record1.setDiagnosisState(isIiagnosis);
        Integer isEEG = addRecordParams.getIsEEG();//是否脑电图
        record1.setEncephlogramState(isEEG);
        Integer isCT = addRecordParams.getIsCT();//是否ct
        record1.setCtState(isCT);
        Integer geneState = addRecordParams.getGeneState();//基因状态
        record1.setGeneState(geneState);
        Integer attacksNumber = addRecordParams.getAttacksNumber();//发作次数
        record1.setAttacksNumber(attacksNumber);
        Integer attacksFrequency = addRecordParams.getAttacksFrequency();//发作频率（1 日 2周 3月）
        record1.setAttacksFrequency(attacksFrequency);
        Integer medicationState = addRecordParams.getMedicationState();//是否药物治疗
        record1.setMedicationState(medicationState);
        Integer operationState = addRecordParams.getOperationState();//是否手术
        record1.setOperationState(operationState);
        Integer hormoneState = addRecordParams.getHormoneState();//是否甲强激素治疗
        record1.setHormoneState(hormoneState);
        Integer immuneState = addRecordParams.getImmuneState();//是否免疫治疗状态
        record1.setImmuneState(immuneState);
        Integer ketogenicState = addRecordParams.getKetogenicState();//是否生酮饮食状态（1 是 2否）
        record1.setKetogenicState(ketogenicState);
        Integer otherState = addRecordParams.getOtherState();
        record1.setOtherState(otherState);
        int insert1 = nowHistoryMapper.insert(record1);
        if(insert1!=1){
            return  ApiResult.failure("添加失败");
        }
        Integer nowhistoryId = record1.getNowhistoryId();
        if(isIiagnosis==1){
            List<Integer> symptomIds = addRecordParams.getSymptomIds();
            List<Integer> diseaseOnsetIds = addRecordParams.getDiseaseOnsetIds();
            if(symptomIds==null||symptomIds.size()==0){
                return ApiResult.failure("诊断症状不能为空");
            }
            if(diseaseOnsetIds==null||diseaseOnsetIds.size()==0){
                return ApiResult.failure("综合症不能为空");
            }
            nowHistoryMapper.addSymptoms(nowhistoryId,symptomIds);
            nowHistoryMapper.addDiseaseOnsets(nowhistoryId,diseaseOnsetIds);
        }
        if(isEEG==2){
            List<Integer> integers = addRecordParams.geteEGIds();
            if(integers==null||integers.size()==0){
                return ApiResult.failure("脑电图不能为空");
            }
            nowHistoryMapper.insertegIds(nowhistoryId,integers);
        }
        if(isCT==2){
            List<Integer> ctIds = addRecordParams.getCtIds();
            if(ctIds==null||ctIds.size()==0){
                return ApiResult.failure("ct异常不能为空");
            }
            nowHistoryMapper.addCtIds(nowhistoryId,ctIds);
        }
        if(medicationState==1){
            List<Integer> drugIds = addRecordParams.getDrugIds();
            if(drugIds==null||drugIds.size()==0){
                return ApiResult.failure("药物治疗药品不能为空");
            }
            nowHistoryMapper.addDrug(nowhistoryId,drugIds);
        }
        if(operationState==1){
            List<Integer> operationIds = addRecordParams.getOperationIds();
            if(operationIds==null||operationIds.size()==0){
                return ApiResult.failure("手术不能为空");
            }
            nowHistoryMapper.addOperation(nowhistoryId,operationIds);
        }
        BeforeHistory record2 = new BeforeHistory();
        Integer drugAllergyState = addRecordParams.getDrugAllergyState();//是否药物过敏
        record2.setDrugallergyState(drugAllergyState);
        Integer traumaState = addRecordParams.getTraumaState();//是否有外伤史
        record2.setTraumaState(traumaState);
        if(traumaState==1){
            String traumaContent = addRecordParams.getTraumaContent();//外伤内容
            record2.setTraumaContent(traumaContent);
        }
        Integer chronicstate = addRecordParams.getChronicstate();//慢病史
        record2.setChronicState(chronicstate);
        Integer injuryState = addRecordParams.getInjuryState();//产伤状态
        record2.setInjuryState(injuryState);
        Integer infectedState = addRecordParams.getInfectedState();//是否感染
        record2.setInfectedState(infectedState);
        Integer hemorrhageState = addRecordParams.getHemorrhageState();//出血
        record2.setHemorrhageState(hemorrhageState);
        Integer convulsionsState = addRecordParams.getConvulsionsState();//是否高热惊厥史（1 是   2 否）
        record2.setConvulsionsState(convulsionsState);
        beforeHistoryMapper.insert(record2);
        Integer beforehistoryId = record2.getBeforehistoryId();
        if(drugAllergyState==1){
            List<Integer> drugAllergyIds = addRecordParams.getDrugAllergyIds();
            if(drugAllergyIds==null||drugAllergyIds.size()==0){
                return ApiResult.failure("过敏药物不能为空");
            }
            beforeHistoryMapper.addDrugAllergy(beforehistoryId,drugAllergyIds);
        }
        if(chronicstate==1){
            List<Integer> chronicIds = addRecordParams.getChronicIds();
            if(chronicIds==null||chronicIds.size()==0){
                return ApiResult.failure("慢病史不能为空");
            }
            beforeHistoryMapper.addChronic(beforehistoryId,chronicIds);
        }
        FamilyHistory record3 = new FamilyHistory();
        Integer inheritanceState = addRecordParams.getInheritanceState();//是否有家族病
        record3.setInheritanceState(inheritanceState);
        Integer marryState = addRecordParams.getMarryState();//是否结婚
        record3.setMarryState(marryState);
        Integer birthState = addRecordParams.getBirthState();//是否生育
        record3.setBirthState(birthState);
        familyHistoryMapper.insert(record3);
        Integer familyhistoryId = record3.getFamilyhistoryId();
        if(inheritanceState==1){
            List<Integer> inheritanceIds = addRecordParams.getInheritanceIds();
            if(inheritanceIds==null||inheritanceIds.size()==0){
                return ApiResult.failure("家族病不能为空");
            }
            familyHistoryMapper.addInheritance(familyhistoryId,inheritanceIds);
        }
        Record record = new Record();
        record.setPatientId(addRecordParams.getPatient_id());
        record.setCreatetime(new Date());
        record.setNowhistoryId(nowhistoryId);
        record.setBeforehistoryId(beforehistoryId);
        record.setFamilyhistoryId(familyhistoryId);
        int insert = recordMapper.insert(record);
        Integer recordId = record.getRecordId();
        visitRecords.setRecord_id(recordId);

        visitRecordsMapper.updateByPrimaryKeySelective(visitRecords);
        return  ApiResult.withBoolean(insert==1,"添加病例成功","添加病例失败");
    }


}
